window.onload = function() {
    var btn = document.querySelector('.login-btn');
        btn.onclick = function() {
        // 获取数据
        var username = document.querySelector('.username').value;
        var password = document.querySelector('.password').value;
        // 数据校验 - 只验证数据不为空
        if(username === '') {
            alert('用户名不能为空')
            return false
        }
        if(password === '') {
            alert('密码不能为空')
            return false
        }

        // 发送ajax请求
        ajax({
            url: '/api/login',
            method: 'post',
            data: {
                username,
                password,
            },
            fn: function(res) {
                res = JSON.parse(res)
                if(res.code === 1) {
                    // alert(res.msg)
                    // 登录成功跳转之前 - 存储cookie
                    setCookie('username', username, 7200)
                    // 跳转
                    // location.href = "index.html"
                    layer.msg(res.msg, {
                        icon: 1,
                        time: 2000
                    }, function() {
                        // 判断本地存储是否存储过url
                        var url = localStorage.getItem('url')
                        if(!url) location.href = '/'
                        else {
                            localStorage.removeItem('url')
                            location.href = url
                        }
                    })

                }else {
                    layer.msg(res.msg, {
                        icon: 2,
                        time: 2000
                    })
                }
            }
        })
    }
}